#include <unistd.h>
#include <iostream>
#include <string>
#include <fcntl.h>
#include <fstream>

#define BUFFER_SIZE 50
std::streamsize TotalSize = -1;
static int changednum = 0;
int main()
{
    //1.清屏，这里需要创建子进程，否则程序会直接退出
    pid_t pid1 = fork();
    if(pid1 == 0) //子进程
    {
        execlp("clear", "clear", nullptr);
    }
    while(1)
    {
        sleep(1);
        //2.提示用户输入要检测其状态的文件名
        std::cout << "Input file name: " << std::endl;
        std::string buffer;
        buffer.resize(BUFFER_SIZE);
        std::cin >> buffer;
        
        //3.显示该文件的状态信息，找不到文件时进行错误提示
        int fd = open(buffer.c_str(), O_RDONLY);
        if(fd == -1)
        {
            std::cout << "Can't find the file [" << buffer << "]!" << std::endl; 
            continue;
        }
        pid_t pid2 = fork();
        if(pid2 == 0)
        {
            //子进程
            execlp("ls", "ls", "-l", buffer.c_str(), nullptr);
        }
        while(1)
        {
            //4.获取文件的大小
            sleep(1);
            std::ifstream file(buffer.c_str(), std::ios::binary | std::ios::ate);
            if(!file)
            {
                std::cerr << "Failed to open" << std::endl;
                return -1;
            }
            std::streamsize size = file.tellg();
            file.close();
            if(size == TotalSize || TotalSize == -1)
            {
                std::cout << "test file's status ..." << std::endl;
                std::cout << std::endl;
                TotalSize = size;
            }
            else
            {
                changednum++;
                std::cout << "file[" << buffer << "]size changed" << std::endl;
                std::cout << "File size:" << size << " bytes" << std::endl;
                if(changednum == 2)
                {
                    std::cout << "Changed number exceed two, test end!" << std::endl;;
                    return 0;
                }
                std::cout << std::endl;
            }
            sleep(4);
        }
    }
    return 0;
}